//
//  FWRadioButtonGroup.m
//  vImageStudy
//
//  Created by Evan Xie on 8/7/15.
//  Copyright (c) 2015 Family Wings. All rights reserved.
//

#import "FWRadioButtonGroup.h"


@interface FWRadioButtonGroup () <FWRadioButtonDelegate>
{
    NSMutableArray *_radioButtons;
}
@end


@implementation FWRadioButtonGroup

- (instancetype)init
{
    return [self initWithRadioButtons:nil];
}

- (instancetype)initWithRadioButtons:(NSArray *)radioButtons
{
    if (self = [super init]) {
        _radioButtons = [NSMutableArray arrayWithCapacity:radioButtons.count];
        _selectedIndex = -1;
    
        [self addRadioButtons:radioButtons];
    }
    
    return self;
}

- (void)addRadioButton:(FWRadioButton *)radioButton
{
    if (![radioButton isKindOfClass:[FWRadioButton class]]) {
        return;
    }
    
    if ([_radioButtons containsObject:radioButton]) {
        return;
    }
    
    radioButton.delegate = self;
    [_radioButtons addObject:radioButton];
}

- (void)addRadioButtons:(NSArray *)radioButtons
{
    if (radioButtons.count == 0) {
        return;
    }
    
    [radioButtons enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([obj isKindOfClass:[FWRadioButton class]] && ![_radioButtons containsObject:obj]) {
            ((FWRadioButton *)obj).delegate = self;
            [_radioButtons addObject:obj];
        }
    }];
}

- (void)selectRadioButton:(FWRadioButton *)radioButton
{
    self.selectedIndex = [_radioButtons indexOfObject:radioButton];
}

- (void)setSelectedIndex:(NSInteger)selectedIndex
{
    if (selectedIndex < 0 || selectedIndex > _radioButtons.count - 1 || _selectedIndex == selectedIndex) {
        return;
    }
    
    _selectedIndex = selectedIndex;
    [_radioButtons[selectedIndex] setSelected:YES];
}

- (void)updateButtonGroup
{
    [_radioButtons enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (idx != self.selectedIndex) {
            [obj setSelected:NO];
        }
    }];
}

#pragma mark - RadioButtonDelegate

- (void)radioButtonDidSelect:(FWRadioButton *)radioButton
{
    NSInteger selectedIndex = [_radioButtons indexOfObject:radioButton];
    _selectedIndex = selectedIndex;
    
    [self updateButtonGroup];
    
    if ([self.delegate respondsToSelector:@selector(radioButtonGroup:didSelectAtIndex:)]) {
        [self.delegate radioButtonGroup:self didSelectAtIndex:selectedIndex];
    }
}

@end
